﻿using Api.Shared.Model;
using Api.Shared.Model.Yanji;
using Api.Shared.MyPlc.S7;
using Api.Shared.Sugar;
using Api.Shared.Utils;
using Api.Shared.Utils.Yanji;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FitterTest.Controllers
{
    [Route("api/private/v1/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class DeviceHisController : ControllerBase
    {
        private readonly ISugarClientService helper;
        private readonly IS7ConnService s7;
        private readonly Db95DeviceHis db95DeviceHis;

        public DeviceHisController(
            [FromKeyedServices(nameof(SqlName.sqlite))] ISugarClientService helper,
            IS7ConnService s7,
            Db95DeviceHis db95DeviceHis
        )
        {
            this.helper = helper;
            this.s7 = s7;
            this.db95DeviceHis = db95DeviceHis;
        }

        [HttpGet]
        public async Task<ActionResult<MyApiResponse<List<DeviceHis>>>> GetDeviceHis([FromQuery] QueryInfo queryInfo)
        {
            if (queryInfo.Pagenum <= 0)
            {
                var a1 = new MyApiResponse<List<DeviceHis>>(false, new());
                return new(a1);
            }
            if (queryInfo.Pagesize <= 0)
            {
                return BadRequest(new MyApiResponse<List<DeviceHis>>(false, new()));
            }
            int totalNumber = 0;

            var exp = Expressionable.Create<DeviceHis>();

            exp.AndIF(
                !string.IsNullOrWhiteSpace(queryInfo.Query),
                x => x.Comment1.Contains(queryInfo.Query)
            );

            exp.AndIF(queryInfo.DateStart != null, x => x.Time > queryInfo.DateStart);

            exp.AndIF(queryInfo.DateEnd != null, x => x.Time < queryInfo.DateEnd);

            exp.AndIF(
                queryInfo.DateEnd != null && queryInfo.DateStart != null,
                x => (x.Time < queryInfo.DateEnd && x.Time > queryInfo.DateStart)
            );

            //vue 分页仅仅 需要总数量 和 当前页. 而handycontrol 需要 总页数(用总数量算出来) 和当前页. 都不需要sqlsugar的 totalpage 总页数
            RefAsync<int> total = 0;

            var a = await helper
                .Db.Queryable<DeviceHis>()
                .ToPageListAsync(queryInfo.Pagenum, queryInfo.Pagesize, total);

            var time = db95DeviceHis;
            if (time == null)
            {
                time = new();
            }
            var aa = new MyApiResponse<List<DeviceHis>>(true, a);
            aa.Total = total;
            aa.Pagenum = queryInfo.Pagenum;
            return aa;
        }
    }
}
